import React, { useState, useCallback } from 'react'
import { NextPage } from 'next'
import { Badge, Popconfirm, message } from 'antd'

import { AdminLayout } from '@/layout';
import { SPTDataTable } from '@/components/SPTDataTable';
import { SearchApi } from '@/api/search'

const Search: NextPage = () => {
  const [records, setRecords] = useState(null);
  const [params, setParams] = useState(null);
  const [loading, setLoading] = useState(false);

  const getSearchRecord = useCallback((params) => {
    setLoading(true);
    return SearchApi.getRecords(params).then(res => {
      setRecords(res[0]);
      setParams(params);
      setLoading(false);
      return res;

    })
  }, [])
  const deleteSearch = (id) => {
    SearchApi.deleteRecord(id).then(res => {
      message.success("删除成功");
      getSearchRecord(params);
    })
  }

  const columns = [
    {
      title: "搜索词",
      key: 'keyword',
      dataIndex: 'keyword',
    },
    {
      title: "搜索量",
      key: 'count',
      render: (_, record) => (
        <Badge count={record.count || 0}
          showZero={true}
          overflowCount={Infinity}
          style={{ backgroundColor: '#52c41a' }} />
      )
    },
    {
      title: "搜索时间",
      key: 'createAt',
      render: (_, record) => (record.createAt)
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        return (
          <Popconfirm title="删除记录" okText="删除" cancelText="取消" onConfirm={() => deleteSearch(record.id)}>
            <a>删除</a>
          </Popconfirm>
        )
      }
    }
  ]
  return (
    <AdminLayout>
      <SPTDataTable data={records} defaultTotal={0} columns={columns} onSearch={getSearchRecord} searchFields={[
        {
          label: '类型',
          field: 'type',
          msg: '请输入类型'
        },
        {
          label: '搜索量',
          field: 'count',
          msg: '输入搜索量',
        },
        {
          label: '搜索词',
          field: 'keyword',
          msg: '输入搜索词'
        }
      ]} />
    </AdminLayout>
  )
}


export default Search;